package com.csxy.six.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class AuthFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String path = exchange.getRequest().getPath().value();

        // 公开路径不需要认证
        if (path.startsWith("/club/public") ||
                path.startsWith("/material/public") ||
                // Swagger UI 路径 - 添加更宽松的匹配
                path.contains("swagger") ||
                path.contains("api-docs") ||
                path.contains("webjars")) {
            return chain.filter(exchange);
        }

        // 检查认证头
        String token = exchange.getRequest().getHeaders().getFirst("Authorization");
        if (token == null || !token.startsWith("Bearer ")) {
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }

        // 验证token逻辑
        if (!isValidToken(token)) {
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }

        return chain.filter(exchange);
    }

    private boolean isValidToken(String token) {
        // 实际项目中应调用认证服务验证token
        return token.length() > 10;
    }

    @Override
    public int getOrder() {
        return -1;
    }
}